<template lang="html">
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="160px">
      <el-form-item label="服务标题">
        <el-input class="inputWidth" v-model="form.service_name"></el-input>
      </el-form-item>
      <el-form-item label="服务一级分类">
        <el-select v-model="form.service_branch_id" @change="classTwo" placeholder="请选择">
          <el-option
            v-for="item in optionsOneId"
            :key="item.eq"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务二级分类">
        <el-select v-model="form.service_classify_id" placeholder="请选择">
          <el-option
            v-for="item in optionsTwoId"
            :key="item.eq"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务轮播">
        <el-row>
          <img v-for="n in imageUrl1" :src="n" class="showLun">
          <el-upload
            class="avatar-uploader"
            :action=domain
            :http-request=lunbo
            :show-file-list="false"
            :before-upload="beforeUpload">
            <img v-if="false" :src="imageUrl1" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-row>
        <el-row>
          <el-upload
            class="upload-demo"
            drag
            :before-upload="beforeUploadVideo"
            :action=domain
            :http-request=video
            :show-file-list="true"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将视频拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-row>
      </el-form-item>
      <el-form-item label="拼团开始时间">
        <el-date-picker
          v-model="ping_begin_time"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="拼团结束时间">
        <el-date-picker
          v-model="ping_end_time"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="服务开始日期">
        <el-col :span="3">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.service_begin_time"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="服务结束日期">
        <el-col :span="3">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.service_end_time"></el-date-picker>
        </el-col>
      </el-form-item>
        <el-form-item label="服务时间段" >
          <div class="demo-input-suffix">
            <el-time-picker type="fixed-time"  value-format="HH:mm" placeholder="选择开始时间" v-model="form.service_time_begin_slot">
            </el-time-picker>
            -
            <el-time-picker type="fixed-time"  value-format="HH:mm" placeholder="选择结束时间" v-model="form.service_time_end_slot">
            </el-time-picker>
          </div>
      </el-form-item>
      <el-form-item label="服务详情图">
        <el-upload
          class="avatar-uploader"
          :action= domain
          :http-request = service
          :show-file-list="false"
          :before-upload="beforeUpload">
          <img v-if="imageUrl2" :src="imageUrl2" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="服务区域">
        <el-select v-model="form.service_area_city" placeholder="请选择活动城市">
          <el-option
            v-for="item in city"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="form.service_area_name" placeholder="请选择活动区域">
          <el-option
            v-for="item in area"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拼团人数">
        <el-input class="inputWidth" placeholder="请输入" type="number" v-model="form.ping_number">
        </el-input>
      </el-form-item>
      <el-form-item label="拼团价格">
        <el-input class="inputWidth" placeholder="请输入" type="number" v-model="form.service_money">
          <template slot="prepend">¥</template>
        </el-input>
        划线价格
        <el-input class="inputWidth" placeholder="请输入" type="number" v-model="form.service_original_money">
          <template slot="prepend">¥</template>
        </el-input>
      </el-form-item>
      <el-form-item label="服务中心">
        <el-input class="address-input" v-model="form.service_address_point[0]" disabled></el-input>
        <el-input class="address-input" v-model="form.service_address_point[1]" disabled></el-input>
        服务范围半径
        <el-input class="inputWidth" type="number" v-model="form.service_address_radius">
          <template slot="prepend">km</template>
        </el-input>
      </el-form-item>
      <el-form-item label="所选地址">
        <el-col :span="6">
          <el-input v-model="form.service_address_name" placeholder="请在下面地图选择地址" disabled></el-input>
        </el-col>
      </el-form-item>
      <MapAdress @drag="dragMap" class="mapbox"></MapAdress>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">发布</el-button>
        <el-button>取消</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate,toDate,toUnix,deleteD } from '@/utils/index'
import MapAdress from '@/views/collage/Map.vue'
export function createClass(mes, url) {
  return request({
    url: url,
    method: 'post',
    data: mes
  })
}
export function token() {
  return request({
    url: '/v1/QNtoken/getToken',
    method: 'get',
  })
}
// parseTime()
export default {
  components: {
    MapAdress
  },
  data() {
    return {
      dragData: {
        lng: null,
        lat: null,
        address: null,
        nearestJunction: null,
        nearestRoad: null,
        nearestPOI: null
      },
      imageUrl1: [],
      imageUrl2: '',
      videoUrl: [],
      token: {},
      domain: 'http://up.qiniu.com',
      qiniuaddr: 'pdsqka1ws.bkt.clouddn.com',
      optionsOneId: [],
      optionsTwoId: [],
      city: [{
        value: '上海',
        label: '上海'
      }],
      area: [{
        value: '上海浦东',
        label: '上海浦东'
      }],
      ping_begin_time: '',
      ping_end_time: '',
      token: '',
      form: {
        service_name: '',
        service_begin_time: '',
        service_end_time: '',
        service_time_begin_slot: '',
        service_time_end_slot: '',
        ping_begin_time: '',
        ping_end_time: '',
        service_video_url: '',
        service_original_money: '120.00',
        service_money: '140.00',
        service_branch_id: '',
        service_classify_id: '',
        service_address_name: '',
        service_address_point: [0,0],
        service_address_radius: '',
        service_area_name: '上海浦东',
        ping_number: '1',
        service_area_city: '上海',
        service_banner_img: [],
        service_content: ''
      },
    }
  },
  created: function() {
    this.form = JSON.parse(localStorage.getItem('reSend')) || this.form
    const n = {
      page: 1,
      size: 9999,
      classify_type: 1
    }
    createClass(n, '/v1/classify').then(res => {
      if (res.code === 200) {
        if (res.data.list.length) {
          res.data.list.filter(item => {
            const val = {
              value: item._id,
              label: item.classify_name,
            }
            this.optionsOneId.push(val)
          })
          // console.log(res);
        }
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    }).catch(error => {
      this.$message({
        message: error,
        type: 'error'
      });
    })
    token().then(res => {
      if (res.code === 200) {
        // console.log(res);
        this.token = res.data.token
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    }).catch(error => {
      this.$message({
        message: error,
        type: 'error'
      });
    })
  },
  methods: {
    dragMap (data) {
      // console.log(data)
      this.dragData = {
        lng: data.position.lng,
        lat: data.position.lat,
        address: data.address,
        nearestJunction: data.nearestJunction,
        nearestRoad: data.nearestRoad,
        nearestPOI: data.nearestPOI
      }
      console.log(this.dragData);
      console.log(this.dragData.address);
      this.form.service_address_name = this.dragData.address;
      this.form.service_address_point = [
        this.dragData.lng,
        this.dragData.lat
      ]
    },
    upqiniu(req, index) {
      console.log(req)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      let filetype = ''
      if (req.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      // 重命名要上传的文件
      const keyname = 'alading' + toUnix(toDate(new Date())) + Math.floor(Math.random() * 100) + '.' + filetype
      // 从后端获取上传凭证token
      const formdata = new FormData()
      formdata.append('file', req.file)
      formdata.append('token', this.token)
      formdata.append('key', keyname)
      // 获取到凭证之后再将文件上传到七牛云空间
      this.axios.post(this.domain, formdata, config).then(res => {
        if (index == 1) {
          const img = 'http://' + this.qiniuaddr + '/' + res.data.key
          this.imageUrl1.push(img)
          console.log(this.imageUrl1);
        } else if (index == 2) {
          console.log(2);
          this.imageUrl2 = 'http://' + this.qiniuaddr + '/' + res.data.key
        }
      })
    },
    video(req) {
      console.log(req)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      const keyname = 'alading' + toUnix(toDate(new Date())) + Math.floor(Math.random() * 100) + '.' + req.file.type
      // 从后端获取上传凭证token
      const formdata = new FormData()
      formdata.append('file', req.file)
      formdata.append('token', this.token)
      formdata.append('key', keyname)
      // 获取到凭证之后再将文件上传到七牛云空间
      if(this.imageUrl1.length+this.videoUrl.length <= 5){
        this.axios.post(this.domain, formdata, config).then(res => {
            const video = 'http://' + this.qiniuaddr + '/' + res.data.key
            // this.videoUrl.push(video)
            this.form.service_video_url=video
        })
      }
    },
    lunbo(n) {
      console.log(this.imageUrl1.length);
      if (this.imageUrl1.length+this.videoUrl.length <= 5) {
        this.upqiniu(n, 1)
        return
      } else {
        return
      }
    },
    service(n) {
      this.upqiniu(n, 2)
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    beforeUploadVideo(file) {
      const isLt10M = file.size / 1024 / 1024  < 50;
      if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
        this.$message.error('请上传正确的视频格式');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传视频大小不能超过10MB哦!');
        return false;
      }
    },
    classTwo() {
      const n = {
        page: 1,
        size: 9999,
        classify_type: 2,
        classify_branch_id: this.form.service_branch_id
      }
      console.log(n);
      this.optionsTwoId = [];
      createClass(n, '/v1/classify').then(res => {
        if (res.code === 200) {
          console.log(res);
          if (res.data.list.length) {
            res.data.list.filter(item => {
              const val = {
                value: item._id,
                label: item.classify_name,
              }
              this.optionsTwoId.push(val)
            })
          }
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })
    },
    getSTime(val) {
      this.sTime = val; //这个sTime是在data中声明的，也就是v-model绑定的值
    },
    onSubmit() {
      let n = this.form
      n.ping_begin_time = toUnix(toDate(this.$data.ping_begin_time));
      n.ping_end_time = toUnix(toDate(this.$data.ping_end_time));
      n.service_begin_time = deleteD(toDate(this.$data.form.service_begin_time))[0]
      n.service_end_time = deleteD(toDate(this.$data.form.service_end_time))[0]
      n.service_banner_img = this.imageUrl1
      n.service_content = this.imageUrl2
      console.log(n)
      createClass(n, '/v1/service/create').then(res => {
        if (res.code === 200) {
          this.$message({
            message: 'success!',
            type: 'success'
          });
          this.$router.go(-1)
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })
    },
    back() {
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader{
    display: inline-block;
    margin: 5px;
  }
  .inputWidth{
    width: 200px;
  }
  .showLun{
    border-radius: 5px;
    width: 200px;
    margin: 10px;
    max-height: 500px;
    float: left;
  }
  .address-input{
    width: 200px;
  }
  .page-header{
  color: #fff; text-align: center; background: #159957;
  background-image: -webkit-linear-gradient(330deg,#155799,#159957);
  background-image: linear-gradient(120deg,#155799,#159957);
  padding: 3rem 4rem; margin-bottom: 30px;
  }
  .m-map{
    margin-bottom: 20px;
    border: 1px solid #cccccc;
  }
  .page-header h1 {
  margin: 0;
  font-size: 40px;
}

.page-header p {
  color: #ccc;
  margin: 0;
  margin-bottom: 30px;
}

.page-header a {
  display: inline-block;
  border: 1px solid #fff;
  margin-right: 10px;
  line-height: 40px;
  padding: 0 20px;
  border-radius: 4px;
  color: #fff;
  text-decoration: none;
  transition: all .3s;
}

.page-header a:hover {
  background: #fff;
  color: #333;
}

.g-wraper {
  width: 1000px;
  margin: 0 auto;
  color: #666;
  font-size: 16px;
  line-height: 30px;
}

.m-part {
  margin-bottom: 30px;
}

.m-part::after {
  content: '';
  display: block;
  clear: both;
}

.m-part .title {
  font-size: 30px;
  line-height: 60px;
  margin-bottom: 10px;
  color: #333;
}

.m-part .mapbox {
  width: 600px;
  height: 400px;
  margin-bottom: 20px;
  float: left;
}

.m-part .info {
  margin: 0;
  padding: 0;
  list-style: none;
  line-height: 30px;
  margin-left: 620px;
}

.m-part .info span {
  display: block;
  color: #999;
}

.m-part ol {
  line-height: 40px;
  margin-left: 0;
  padding-left: 0;
}

.m-part pre {
  padding: 10px 20px;
  line-height: 30px;
  border-radius: 3px;
  box-shadow: 0 0 15px rgba(0, 0, 0, .5);
}

.m-footer {
  background: #eee;
  line-height: 60px;
  text-align: center;
  color: #999;
  font-size: 12px;
}

.m-footer a {
  margin: 0 5px;
  color: #999;
  text-decoration: none;
}
</style>
